<template>
	<el-card class="news-manage-container">
		<div class="manage-header">
			<el-form-item>
				<el-input type="text" placeholder="新闻标题..." v-model="newsTitle"/>
			</el-form-item>
			<el-button type="primary"
			           @click="searchHandler(newsTitle)"
			           :icon="Search"
			>查&nbsp;询
			</el-button>
			<el-button type="primary"
			           @click="resetHandler(searchList)"
			           :icon="Refresh"
			>恢&nbsp;复
			</el-button>
			<el-button type="success"
			           @click="addNews"
			>
				新&nbsp;增
				<el-icon class="el-icon--right">
					<Plus/>
				</el-icon>
			</el-button>
			<el-button type="danger"
			           @click="removeSelect(selectData)"
			>
				删&nbsp;除
				<el-icon class="el-icon--right">
					<Delete/>
				</el-icon>
			</el-button>
		</div>
		<div class="select-container">
			已选择
			<span class="num">{{ selectNum }}</span>
			项
			<span class="btn"
			      @click="clearSelect"
			>清空</span>
		</div>
		<el-table :data="baseTableData"
		          style="width: 100%;max-height: 68vh"
		          table-layout="fixed"
		          @selection-change="selectionChange"
		          ref="tableRef"
		>
			<el-table-column type="selection" width="55"/>
			<el-table-column type="index" label="序号" width="70"/>
			<el-table-column label="标题" prop="news_title">
				<template #default="{row}">
					<div class="news-title">
						{{ row['news_title'] }}
					</div>
				</template>
			</el-table-column>
			<el-table-column label="日期" prop="news_time" width="120"/>
			<el-table-column label="分类"
			                 prop="category"
			                 width="100"
			                 column-key="category_id"
			                 :filters="[
													 {text: '公司新闻',value: 'companyNews'},
													 {text: '企业公告',value: 'companyNotice'},
													 {text: '媒体报道',value: 'companyReport'},
			                 ]"
			                 :filter-method="filterHandler"


			>
				<template #default="{row}">
					<el-tag type="success">{{ row.category }}</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="操作"
			                 fixed="right"
			                 width="220">
				<template #default="{row}">
					<el-button size="small" link type="primary" @click="lookDetail(row)">详情</el-button>
					<el-button size="small" link type="success" @click="previewNews(row['news_id'])">预览</el-button>
					<tooltip-vue content="修改新闻">
						<el-button type="primary" :icon="Edit" size="large" link @click="changeNewsHandler(row)"/>
					</tooltip-vue>
					<tooltip-vue content="删除新闻">
						<el-button type="warning" :icon="Delete" size="large" link @click="removeNews(row)"/>
					</tooltip-vue>
				</template>
			</el-table-column>
		</el-table>
		<div class="pagination-container">
			<el-pagination
					background
					layout="prev, pager, next,total"
					v-model:current-page="paginationData.page"
					v-model:page-size="paginationData.size"
					:page-sizes="[10,15,20]"
					:total="paginationData.total"
					@current-change="handleCurrentChange"
			/>
		</div>
		<change-news v-model="visible"
		             @updateSuccess="updateSuccess"
		             :current-news="currentNews"
		/>
		<news-preview :news-id="currentId" v-model="showModel"/>
	</el-card>
</template>

<script setup>
import TooltipVue from '@/libs/tooltip';
import {computed, onActivated, ref, reactive} from "vue";
import {deleteNews, getNewsList, delNewsList} from '@/api/news';
import ChangeNews from './components/change-news'
import NewsPreview from './components/news-preview';
import {useRouter} from 'vue-router';
import {Plus} from '@element-plus/icons-vue'
import confirm from '@/libs/confirm/index'
import {Edit, Delete, Search, Refresh} from '@element-plus/icons-vue'
import {ElMessage} from "element-plus";

const visible = ref(false),
		tableData = ref([]),
		currentNews = ref({}),
		showModel = ref(false),
		currentId = ref(''),
		selectData = ref([]),
		tableRef = ref(null),
		newsTitle = ref(''),
		searchList = ref([]),
		paginationData = reactive({
			total: 0,
			size: 12,
			page: 1,
		});
const initNewsList = async (size, page) => {
	const {success, list, total} = await getNewsList({
		size,
		page,
	})
	if (!success) return
	paginationData.total = total
	tableData.value = [...list]
}

const handleCurrentChange = (val) => {
	initNewsList(paginationData.size, val)
}
const addNews = () => {
	router.push({name: 'uploadNews'}).catch(() => null)
}
const searchHandler = (keyword) => {
	if (!keyword) {
		return
	}
	searchList.value = [
		...tableData.value.filter(item => {
			return item['news_title'].indexOf(keyword) !== -1
		})
	]
}
const resetHandler = (list) => {
	if (list.length) {
		searchList.value = []
		newsTitle.value = ''
	}
}
const baseTableData = computed(() => {
	if (searchList.value.length) {
		return searchList.value
	}
	return tableData.value
})
const lookDetail = (news) => {
	visible.value = true
	currentNews.value = {...news}
}
const updateSuccess = (news) => {
	visible.value = false
	const {news_id, id} = news
	const idx = tableData.value.findIndex(item => item['news_id'] === news_id && item['id'] === id)
	if (idx === -1) return
	tableData.value[idx] = {...news}
}
const previewNews = (id) => {
	currentId.value = id
	showModel.value = true
}
const router = useRouter()
const changeNewsHandler = ({news_id}) => {
	router.push({
		name: 'uploadNews',
		query: {id: news_id}
	})
}
const removeNews = ({news_id, id}) => {
	confirm({
		message: '你确定删除该条新闻吗?',
		title: '温馨提示',
		cancelBtnText: '取消',
		confirmBtnText: '删除',
	})
			.then(async () => {
				const {success} = await deleteNews({id, news_id})
				if (!success) return
				await initNewsList(paginationData.size, paginationData.page)
			})
			.catch(() => null)
}
const filterHandler = (value, row, column) => {
	const key = column['columnKey']
	const v = row[key]
	return value === v
}
const selectNum = ref(0)
const selectionChange = (val) => {
	selectNum.value = val.length
	selectData.value = [...val]
}
const clearSelect = () => {
	tableRef.value?.clearSelection()
}
const removeSelect = (selectValues) => {
	if (!selectValues.length) {
		ElMessage.warning({
			message: '您还没有选择要删除的新闻!',
			duration: 1500,
		})
		return
	}
	console.log(selectValues)
	confirm({
		message: `你确定要删除 ${selectValues.length} 条数据吗?`,
		title: '温馨提示',
		cancelBtnText: '取消',
		confirmBtnText: '删除',
	})
			.then(async () => {
				const list = selectValues.map(item => {
					const {id, news_id} = item
					return {
						id, news_id,
					}
				})
				const {success} = await delNewsList({
					list,
				})
				if (success) {
					await initNewsList(paginationData.size, paginationData.page)
				}
			})
			.catch(() => null)


}
onActivated(() => {
	initNewsList(paginationData.size, paginationData.page)
})

</script>

<style scoped lang="scss">
.news-manage-container {
	height: 86vh;
	position: relative;

	.manage-header {
		display: flex;
		align-items: center;

		.el-form-item {
			margin-bottom: 0;
			margin-right: 20px;
		}

		.editor-icon {
			color: #fff;
		}
	}

	.select-container {
		border: 1px solid #13ce66;
		background-color: #e7faf0;
		padding: 8px 15px 8px 37px;
		font-size: 14px;
		color: #13ce66;
		word-break: break-word;
		border-radius: 4px;
		line-height: 1.5;
		font-variant: tabular-nums;
		margin: 15px 0;


		.num {
			padding-left: 5px;
			color: #1890FF;
			cursor: pointer;
			transition: color .3s ease;
			font-weight: 600;

			&:hover {
				color: #40a9ff;
			}
		}

		.btn {
			padding-left: 30px;
			cursor: pointer;
			color: #1890FF;
			transition: color .3s ease;

			&:hover {
				color: #40a9ff;
			}
		}
	}

	.news-title {
		min-width: 250px;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.pagination-container {
		display: flex;
		justify-content: center;
		position: absolute;
		bottom: 20px;
		left: 0;
		right: 0;
	}
}
</style>